/**
 * 此模块依赖于jfhttp.js,httppackge.js
 */
angular.module('com.xbstar.msg', [])
.factory("LocalStorageService", function() {
  return {
     get: function localStorageServiceGet(key, defaultValue) {
                var stored = localStorage.getItem(key);
                try {
                    stored = angular.fromJson(stored);
                } catch (error) {
                    stored = null;
                }
                if (defaultValue && stored === null) {
                    stored = defaultValue;
                }
                return stored;
            },
    update: function localStorageServiceUpdate(key, value) {
                if (value) {
                    localStorage.setItem(key, angular.toJson(value));
                }
            },
    clear: function localStorageServiceClear(key) {
                localStorage.removeItem(key);
            }
  };
})
.factory('dateService', [function() {
        return {
            handleMessageDate: function(messages) {
                var i = 0,
                    length = 0,
                    messageDate = {},
                    nowDate = {},
                    weekArray = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
                    diffWeekValue = 0;
                if (messages) {
                    nowDate = this.getNowDate();
                    length = messages.length;
                    for (i = 0; i < length; i++) {
                        messageDate = this.getMessageDate(messages[i]);
                        if(!messageDate){
                            return null;
                        }
                        if (nowDate.year - messageDate.year > 0) {
                            messages[i].lastMessage.time = messageDate.year + "";
                            continue;
                        }
                        if (nowDate.month - messageDate.month >= 0 ||
                            nowDate.day - messageDate.day > nowDate.week) {
                            messages[i].lastMessage.time = messageDate.month +
                                "月" + messageDate.day + "日";
                            continue;
                        }
                        if (nowDate.day - messageDate.day <= nowDate.week &&
                            nowDate.day - messageDate.day > 1) {
                            diffWeekValue = nowDate.week - (nowDate.day - messageDate.day);
                            messages[i].lastMessage.time = weekArray[diffWeekValue];
                            continue;
                        }
                        if (nowDate.day - messageDate.day === 1) {
                            messages[i].lastMessage.time = "昨天";
                            continue;
                        }
                        if (nowDate.day - messageDate.day === 0) {
                            messages[i].lastMessage.time = messageDate.hour + ":" + messageDate.minute;
                            continue;
                        }
                    }
                    // console.log(messages);
                    // return messages;
                } else {
                    console.log("messages is null");
                    return null;
                }

            },
            getNowDate: function() {
                var nowDate = {};
                var date = new Date();
                nowDate.year = date.getFullYear();
                nowDate.month = date.getMonth();
                nowDate.day = date.getDate();
                nowDate.week = date.getDay();
                nowDate.hour = date.getHours();
                nowDate.minute = date.getMinutes();
                nowDate.second = date.getSeconds();
                return nowDate;
            },
            getMessageDate: function(message) {
                var messageDate = {};
                var messageTime = "";
                //2015-10-12 15:34:55
                var reg = /(^\d{4})-(\d{1,2})-(\d{1,2})\s(\d{1,2}):(\d{1,2}):(\d{1,2})/g;
                var result = new Array();
                if (message) {
                    messageTime = message.lastMessage.originalTime;
                    result = reg.exec(messageTime);
                    if (!result) {
                        console.log("result is null");
                        return null;
                    }
                    messageDate.year = parseInt(result[1]);
                    messageDate.month = parseInt(result[2]);
                    messageDate.day = parseInt(result[3]);
                    messageDate.hour = parseInt(result[4]);
                    messageDate.minute = parseInt(result[5]);
                    messageDate.second = parseInt(result[6]);
                    // console.log(messageDate);
                    return messageDate;
                } else {
                    console.log("message is null");
                    return null;
                }
            }
        };
    }])
    .factory('MSGService', function($q,JFHttp,LocalStorageService) {
        /**
         * 用以存储没有读取消息个数的数组
         */
        var MsgNotReadArr={};
        MsgNotReadArr.total=0;
        /**
         * 从服务器获取所有的会话，以及每条会话的前十条，同时会覆盖之前的相应缓存。
         * 此函数通过http请求获取参数
         * 此函数执行时不更新budge
         * @param {} userId 用户编号
         */
        var findAll=function(userId){
            /**
             * 本地存储时分两部分：
             * 1.MsgList 用于存储会话信息，包含字段name（会话名称），imgUrl（会话图片）,lastMsg（最新的发言内容），lastTime（时间），sessionId（会话id）；
             * 2.msg+sessionid进行存储，数组包含字段   headImgUrl(发言人头像)，content（发言内容），msgId（消息编号），sendTime（发言时间）,isFromMe
             */
            JFHttp.post({
                url:"http://106.14.30.199:8080/msg/findallbyuser",
                data:{
                    userId:userId,
                }
            }).then(function(result){
                //1.更新msglist
                var arrs=result.data;
                if(!arrs)return;
                var msglist=[];
                arrs.forEach(function(element) {
                    var mobj={};
                    mobj.sessionId=element.id;
                    mobj.name=element.name;
                    mobj.imgUrl=element.imgUrl;
                    mobj.noReadNum=0;
                    var msgArr=element.msgs;
                    var msgdeatailList=[];
                    if(msgArr){
                        msgArr.forEach(function(ele,index) {
                            if(index==0){
                                mobj.lastTime=ele.sendTime;
                                mobj.lastMsg=ele.content;
                            }
                            var msgde={};
                            msgde.headImgUrl=ele.headImgUrl;
                            msgde.content=ele.content;
                            msgde.isFromMe=ele.isFromMe;
                            msgde.sendTime=ele.sendTime;
                            msgde.nikeName=ele.nikeName;
                            msgde.msgId=ele.msgId;
                            msgdeatailList.unshift(msgde);
                        }, this);
                    }
                    LocalStorageService.update("msg"+mobj.sessionId,msgdeatailList);
                    msglist.unshift(mobj);
                }, this);
                LocalStorageService.update("msgList",msglist);
            },function(result){
                console.error(result);
            });
        };
        /**
         * 获取所有的会话
         */
        var getAllSessions=function(){
            var list=LocalStorageService.get("msgList");
            if(list)return list;
            else return null;
        }
        /**
         * 读取会话中的详细信息
         * @param  {} sessionId 会话编号
         */
        var readSessionById=function(sessionId){
            if(!sessionId)return;
            var changeNum=MsgNotReadArr[""+sessionId]==undefined?0:MsgNotReadArr[""+sessionId];
            // MsgNotReadArr.total-=changeNum;
            // MsgNotReadArr.total=MsgNotReadArr.total<1?0:MsgNotReadArr.total;
            // MsgNotReadArr[""+sessionId]=0;
            //TODO 读取标号并发送事件
            changNOReadNum(0-changeNum,sessionId);
            var ssarr=LocalStorageService.get("msg"+sessionId);
            if(!ssarr)return null;
            else return ssarr;
        }
        /**
         * @param  {} userId 用户编号
         * @param  {} sessionId 会话编号
         * @param  {} content 消息内容
         */
        var sendMsgToSession=function(userId,sessionId,content){
             var deferred=$q.defer();
             JFHttp.post({
                 url:"http://106.14.30.199:8080/msg/tosession",
                 data:{
                     sessionId:sessionId,
                     content:content,
                     userId:userId,
                 }
             }).then(function(result){
                 //更新本地存储
                var arrslist= LocalStorageService.get("msgList");
                if(!arrslist)
                {
                    deferred.reject({status:403});
                    return;
                }
                var tjj=0;
                for(tjj=0;tjj<arrslist.length;tjj++){
                    var tmpobj=arrslist[tjj];
                    if(tmpobj.sessionId==sessionId){
                        tmpobj.lastTime=(new Date()).format("yyyy-MM-dd HH:mm:ss");
                        tmpobj.lastMsg=content;
                        arrslist[tjj]=tmpobj;
                    }
                    // if(tmpobj.sessionId!=sessionId&&tjj==(arrslist.length-1)){

                    // }
                }

                LocalStorageService.update("msgList",arrslist);
                var ssarr=LocalStorageService.get("msg"+sessionId);
                if(!ssarr)ssarr=[];
                var newmsg={};
                newmsg.userId=userId;
                newmsg.sendTime=(new Date()).format("yyyy-MM-dd hh:mm:ss");
                newmsg.isFromMe=true;
                newmsg.msgId=result.data.msgId;
                newmsg.nikeName=result.data.nikeName;
                newmsg.content=content;
                newmsg.headImgUrl=result.data.headImgUrl;
                ssarr.push(newmsg);
                LocalStorageService.update("msg"+sessionId,ssarr);
                 deferred.resolve({
                     data:newmsg,
                 });
             },function(result){
                  deferred.reject(result);
             });
              return deferred.promise;
        };
         var appElement = document.querySelector('#msgewerr');
        /**
         * 用于消息监听中的消息时间分发
         * 当im中有消息传来时，由此函数进行分发事件，给顶层元素绑定事件
         */
        var onMsgReceive=function(msg){
            if(!msg)return;
             var arrslist= LocalStorageService.get("msgList");
             var tjj=0;
             var msgs=[];
             var mgslength=arrslist.length;
             if(mgslength==0){
                    var fffs={};
                    fffs.lastTime=msg.sendTime;
                    fffs.lastMsg=msg.content;
                    fffs.sessionId=msg.sessionId;
                    fffs.name=msg.sessionName;
                    fffs.imgUrl=msg.imgUrl;
                    arrslist.unshift(fffs);
                    msgs.push(msg);
                     LocalStorageService.update("msg"+msg.sessionId,msgs);
             }
             for(tjj=0;tjj<mgslength;tjj++){
                var tmpobj=arrslist[tjj];
                if(tmpobj.sessionId==msg.sessionId){
                    tmpobj.lastTime=msg.sendTime;
                    tmpobj.lastMsg=msg.content;
                    arrslist[tjj]=tmpobj;
                    msgs=LocalStorageService.get("msg"+msg.sessionId);
                    msgs.push(msg);
                    LocalStorageService.update("msg"+msg.sessionId,msgs);
                    break;
                    //MsgNotReadArr[""+msg.sessionId]+=1;
                }else if(tjj==arrslist.length-1){
                    var fffs={};
                    fffs.lastTime=msg.sendTime;
                    fffs.lastMsg=msg.content;
                    fffs.sessionId=msg.sessionId;
                    fffs.name=msg.sessionName;
                    fffs.imgUrl=msg.imgUrl;
                    arrslist.unshift(fffs);
                    msgs.push(msg);
                     LocalStorageService.update("msg"+msg.sessionId,msgs);
                     break;
                    //MsgNotReadArr[""+msg.sessionId]=1;
                }
             }
            LocalStorageService.update("msgList",arrslist);
            ionic.trigger("msgreceive",{target:appElement,msg:msg});
        };
        /**
         * 对未消息进行修改，以及发送未读消息进行广播
         * @param  {} changNum 正值表示增加，负值表示减少
         * @param  {} sessionId
         */
        var changNOReadNum=function(changNum,sessionId){
            if(!sessionId)return;
            var num=0;
            if(!isNaN(changNum)){
                try {
                    num=parseInt(changNum);
                } catch (error) {
                    console.log(error);
                }
            }else{
                num=changNum;
            }
            //var noww=parseInt(MsgNotReadArr[""+sessionId]==undefined?0:MsgNotReadArr[""+sessionId]);
            if(isNaN( MsgNotReadArr[""+sessionId])) MsgNotReadArr[""+sessionId]=0;
             MsgNotReadArr[""+sessionId]+=num;
              MsgNotReadArr[""+sessionId]=MsgNotReadArr[""+sessionId]<1?0: MsgNotReadArr[""+sessionId];
             MsgNotReadArr.total+=num;
             MsgNotReadArr.total=MsgNotReadArr.total<1?0:MsgNotReadArr.total;
             ionic.trigger("msgnoreadchange",{target:appElement,msg:MsgNotReadArr});
        };
        /**
         * 新建一个会话到某一个用户
         * @param  {} from
         * @param  {} to
         */
        var makeAsessionByUser=function(from,to){
            if(!from||!to)return;
            var deferred=$q.defer();
             JFHttp.post({
                 url:"http://106.14.30.199:8080/session/makesession",
                 data:{
                     from:from,
                     to:to
                 }
             }).then(function(result){
                 //更新本地存储
                var arrslist= LocalStorageService.get("msgList");
                if(!arrslist)arrslist=[];
                arrslist.push(result.data);
                LocalStorageService.update("msgList",arrslist);
             
                 deferred.resolve({
                     data:result.data,
                 });
             },function(result){
                  deferred.reject(result);
             });
              return deferred.promise;

        }
         /**
          * 增加未读消息改变事件
          * @param  {} callBack回调函数，接受一个参数
          */
         var addNoReadChangeListener=function(callBack){
             ionic.on("msgnoreadchange",function(event){
                 if(!event.detail.msg)return;
                 var flag=callBack(event.detail.msg);
             },appElement);
         }
        /**
         * 增加收到消息事件回调函数
         * @param  {} callBack 回调函数
         * callBack执行后，如果返回值为假，则进行消息未读的扩散
         * 当接受的消息整好呗阅读时，不进行未读消息扩散，即返回值为真
         * 其他情况均需未读消息扩散
         */
        var sendflag={};
        var addMsgListener=function(callBack){
             ionic.on("msgreceive",function(event){
                 if(!event.detail.msg)return;
                 if(!event.detail.msg.sessionId)return;
                 var flag=callBack(event.detail.msg);

                 if(!flag&&!sendflag[event.detail.msg.msgId])
                 {
                     changNOReadNum(+1,event.detail.msg.sessionId);
                     sendflag[event.detail.msg.msgId]=2;
                 }
            },appElement);
        };
        return{
            findAll:function(userId){
                return findAll(userId);
            },
            sendMsgToSession:function(userId,sessionId,content){
                return sendMsgToSession(userId,sessionId,content);
            },
            onMsgReceive:function(msg){
                return onMsgReceive(msg);
            },
            addMsgListener:function(callBack){
                return addMsgListener(callBack);
            },
            readSessionById:function(id){
                return readSessionById(id);
            },
            addNoReadChangeListener:function(callBack){
                return addNoReadChangeListener(callBack);
            },
            // readSessionById:function(id){
            //     readSessionById(id);
            // },
            getAllSessions:function(){
                return getAllSessions();
            },
            changNOReadNum:function(changeNum,sessionId){
                return changNOReadNum(changeNum,sessionId)
            },
            msgNotReadArr:MsgNotReadArr,
            makeAsessionByUser:function(from,to){
                return makeAsessionByUser(from,to);
            }
        };

    })
.directive('jfMsgBrodcast', function ($rootScope) {
    return {
        restrict: 'E',
        template: '<div id="msgewerr" style="display:none"></div>',
        replace: true,
    };
})
.filter('notReadMsg',function(MSGService){
    return function(inputArr){
        if(!inputArr)return;
        var notReadMsg=MSGService.msgNotReadArr;
        if(inputArr=='total'){
            var total=notReadMsg['total'];
            if(total>99){
                return "99+"
            }else{
                return total;
            }
        }else{
            var dd=notReadMsg[""+sessionId];
            if(!dd)return false;
            if(dd>0)return true;
        }
    }
})